import jwt
from django.core.cache import cache
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from the_flash.settings import SECRET_KEY
from user.models import UserModel
from utils.errors import ParamException


class CustomAuthentication(BaseAuthentication):

    def authenticate(self, request):
        path = request.path  # 获取当前路由地址
        print(path)
        not_need_auth = [
                         '/api/user/login/',
                         ]
        if path in not_need_auth:
            return None
        token = request.META.get('HTTP_TOKEN')
        if token:
            try:
                result = jwt.decode(token, SECRET_KEY, algorithm='HS256')
                user = UserModel.objects.get(userid=result['data']['user_id'])
                return user, token
            except Exception:
                pass
        raise AuthenticationFailed('请提供有效的身份认证标识')

# class UserAuth(BaseAuthentication):
#     # 用户认证类，类似中间键
#     def authenticate(self, request):
#         # 登录地址才需要做token判断
#         # 不需要做登录认证的地址不需要做认证
#         path = request.path    # 获取当前路由地址
#         not_need_auth = ['/api/user/auth/register/',
#                          '/api/user/auth/login/',
#                          '/api/goods/foodtype/',
#                          '/api/goods/market/',
#                          '/api/goods/home/']
#         if path in not_need_auth:
#             return None
#
#         token = request.data.get('token') if request.data.get('token') else request.query_params.get('token')
#         if token:
#             user_id = cache.get(token)
#             if user_id:
#                 user = UserModel.objects.filter(id=user_id).first()
#                 if user:
#                     return user, token
#         res = {'code': 2000, 'msg': '用户未登录'}
#         raise ParamException(res)
